<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import type { FormInstance, TableColumnsType } from 'ant-design-vue';
import {
  type CurveConfig,
  type CurveConfigSearchParams,
  type CurveDefinitionDTO,
  createCurveConfig,
  deleteCurveConfig,
  fetchCurveConfigList,
  fetchCurveDefinitionList,
  fetchCurveDefinitionsByCurrency
} from '@/service/api/curve-config';
import { fettchProductDefinitions } from '@/service/api/product-model-mapping';

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const formRef = ref<FormInstance>();

// 搜索表单
const searchForm = reactive({
  curveName: '',
  curveType: '',
  currency: ''
});

// 表单数据
const formData = reactive<Partial<CurveConfig>>({
  id: undefined,
  currency: '',
  type: '',
  fxContract: '',
  idx: '',
  typology: '',
  desk: '',
  generator: '',
  curveType: '',
  curveName: '',
  description: '',
  configParams: '',
  status: 1
});

// 表格数据
const tableData = ref<CurveConfig[]>([]);

// 产品类别选项
const productTypeOptions = ref<Array<{ label: string; value: string }>>([]);

// 曲线定义选项
const curveDefinitionOptions = ref<Array<{ label: string; value: string }>>([]);

// 表格筛选函数
const onFilter = (value: string | number | boolean, record: CurveConfig, dataIndex: string) => {
  return String(record[dataIndex as keyof CurveConfig])
    .toLowerCase()
    .includes(String(value).toLowerCase());
};

/** 获取指定列的唯一值并生成筛选选项 */
const getUniqueFilters = (dataIndex: string) => {
  const uniqueValues = [...new Set(tableData.value.map(item => item[dataIndex as keyof CurveConfig]))]
    .filter(value => value !== null && value !== undefined && value !== '')
    .map(value => ({
      text: String(value),
      value: String(value)
    }));
  return uniqueValues;
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条数据`
});

// 表格列定义
const columns: TableColumnsType<CurveConfig> = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    customRender: ({ index }) => index + 1 + (pagination.current - 1) * pagination.pageSize
  },
  {
    title: '币种',
    dataIndex: 'currency',
    key: 'currency',
    width: 100,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'currency')
  },
  {
    title: '产品类别',
    dataIndex: 'type',
    key: 'type',
    width: 120,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'type')
  },
  {
    title: 'FX合约',
    dataIndex: 'fxContract',
    key: 'fxContract',
    width: 120,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'fxContract')
  },
  {
    title: '指标',
    dataIndex: 'idx',
    key: 'idx',
    width: 200,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'idx')
  },
  {
    title: '类型学',
    dataIndex: 'typology',
    key: 'typology',
    width: 120,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'typology')
  },
  {
    title: '交易台',
    dataIndex: 'desk',
    key: 'desk',
    width: 100,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'desk')
  },
  {
    title: '生成器',
    dataIndex: 'generator',
    key: 'generator',
    width: 120,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'generator')
  },
  {
    title: '曲线类型',
    dataIndex: 'curveType',
    key: 'curveType',
    width: 120,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'curveType')
  },
  {
    title: '曲线名称',
    dataIndex: 'curveName',
    key: 'curveName',
    width: 200,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'curveName')
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    width: 200,
    ellipsis: true,
    filters: [],
    onFilter: (value: string | number | boolean, record: CurveConfig) => onFilter(value, record, 'description')
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
];

/** 更新所有列的筛选选项 */
const updateFilters = () => {
  const filterColumns = [
    'currency',
    'type',
    'fxContract',
    'idx',
    'typology',
    'desk',
    'generator',
    'curveType',
    'curveName',
    'description'
  ];

  filterColumns.forEach(columnKey => {
    const column = columns.find(col => col.key === columnKey);
    if (column && column.filters !== undefined) {
      column.filters = getUniqueFilters(columnKey);
    }
  });
};

// 表单验证规则
const formRules = {
  curveName: [{ required: true, message: '请输入曲线名称', trigger: 'blur' }],
  curveType: [{ required: true, message: '请选择曲线类型', trigger: 'change' }],
  currency: [{ required: true, message: '请输入币种', trigger: 'blur' }]
} as any;

/** 重置表单数据 */
function resetForm() {
  formData.id = undefined;
  formData.currency = '';
  formData.type = '';
  formData.fxContract = '';
  formData.idx = '';
  formData.typology = '';
  formData.desk = '';
  formData.generator = '';
  formData.curveType = '';
  formData.curveName = '';
  formData.description = '';
  formData.configParams = '';
  formData.status = 1;
}

/** 获取产品类别选项 */
const fetchProductTypes = async () => {
  try {
    const response = await fettchProductDefinitions();
    console.info(response);
    if (response.data) {
      // 从产品定义中提取唯一的产品类别
      const uniqueTypes = [...new Set(response.data.map(item => item.code))]
        .filter(category => category && category.trim() !== '')
        .map(category => ({
          label: category,
          value: category
        }));
      productTypeOptions.value = uniqueTypes;
    }
  } catch (error) {
    console.error('获取产品类别失败:', error);
  }
};

// 存储所有曲线定义数据
const allCurveDefinitions = ref<CurveDefinitionDTO[]>([]);

/** 根据币种更新曲线选项 */
const updateCurveOptions = async () => {
  const currency = formData.currency;
  if (currency) {
    try {
      // 根据币种从后端获取对应的曲线
      const response = await fetchCurveDefinitionsByCurrency(currency);
      if (response.data) {
        console.info('fetchCurveDefinitionsByCurrency:', response);
        curveDefinitionOptions.value = response.data
          // .filter((item: CurveDefinitionDTO) => item.status === 1)
          .map((item: CurveDefinitionDTO) => ({
            label: item.curveName,
            value: item.curveName
          }));
      }
    } catch (error) {
      console.error('根据币种获取曲线定义失败:', error);
      // 如果API调用失败，回退到本地筛选
      curveDefinitionOptions.value = allCurveDefinitions.value
        .filter((item: CurveDefinitionDTO) => (item as any).currencyCode === currency)
        .map((item: CurveDefinitionDTO) => ({
          label: item.curveName,
          value: item.curveName
        }));
    }
  } else {
    // 如果没有选择币种，显示所有曲线
    curveDefinitionOptions.value = allCurveDefinitions.value.map((item: CurveDefinitionDTO) => ({
      label: `${item.curveName} (${(item as any).currencyCode || (item as any).currency})`,
      value: item.curveName
    }));
  }
};

/** 获取曲线定义选项 */
const fetchCurveDefinitions = async () => {
  try {
    const response = await fetchCurveDefinitionList();
    if (response.data) {
      allCurveDefinitions.value = response.data.filter((item: CurveDefinitionDTO) => (item as any).status === 1);
      await updateCurveOptions();
    }
  } catch (error) {
    console.error('获取曲线定义失败:', error);
  }
};

/** 币种变化时的处理 */
const onCurrencyChange = async () => {
  // 清空曲线名称选择
  formData.curveName = '';
  // 更新曲线选项
  await updateCurveOptions();
};

/** 获取数据列表 */
const fetchData = async () => {
  loading.value = true;
  try {
    const params: CurveConfigSearchParams = {
      curveName: searchForm.curveName || undefined,
      curveType: searchForm.curveType || undefined,
      currency: searchForm.currency || undefined,
      current: pagination.current,
      size: pagination.pageSize
    };

    const response = await fetchCurveConfigList(params);

    if (response.data) {
      // 后端返回的是直接的数组数据，不是分页结构
      tableData.value = Array.isArray(response.data) ? response.data : [];
      pagination.total = Array.isArray(response.data) ? response.data.length : 0;
      pagination.current = params.current || 1;

      // 更新筛选选项
      updateFilters();
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    window.$message?.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

/** 搜索数据 */
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

/** 重置搜索条件 */
const handleReset = () => {
  searchForm.curveName = '';
  searchForm.curveType = '';
  searchForm.currency = '';
  handleSearch();
};

/** 新增记录 */
const handleAdd = () => {
  resetForm();
  modalVisible.value = true;
};

/** 删除记录：根据ID删除一条曲线映射记录 */
const handleDelete = async (record: CurveConfig) => {
  try {
    if (!record.id) {
      window.$message?.warning('该记录缺少ID，无法删除');
      return;
    }

    const { data: resData, error: err } = await deleteCurveConfig(record.id);

    if (resData && !err) {
      window.$message?.success('删除成功');
      fetchData();
    } else {
      // 失败信息由拦截器统一处理，这里不再重复提示
    }
  } catch (error) {
    console.error('删除失败:', error);
    // 兜底错误提示（网络异常等未进入拦截器场景）
    window.$message?.error('删除失败');
  }
};

/** 提交表单 */
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    await createCurveConfig({
      currency: formData.currency!,
      type: formData.type!,
      fxContract: formData.fxContract!,
      idx: formData.idx!,
      typology: formData.typology!,
      desk: formData.desk!,
      generator: formData.generator!,
      curveType: formData.curveType!,
      curveName: formData.curveName!,
      description: formData.description!,
      configParams: formData.configParams!,
      status: formData.status!
    });
    window.$message?.success('创建成功');

    modalVisible.value = false;
    fetchData();
  } catch (error) {
    console.error('提交失败:', error);
    window.$message?.error('操作失败');
  }
};

/** 取消操作 */
const handleCancel = () => {
  modalVisible.value = false;
  resetForm();
};

/** 表格变化处理 */
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchData();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
  fetchProductTypes();
  fetchCurveDefinitions();
});
</script>

<template>
  <div>
    <ACard title="曲线映射管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="mb-4">
        <ARow :gutter="16">
          <ACol :span="6">
            <AInput v-model:value="searchForm.curveName" placeholder="请输入曲线名称" allow-clear />
          </ACol>
          <ACol :span="6">
            <ASelect v-model:value="searchForm.curveType" placeholder="请选择曲线类型" allow-clear style="width: 100%">
              <ASelectOption value="YIELD">收益率曲线</ASelectOption>
              <ASelectOption value="DISCOUNT">贴现曲线</ASelectOption>
              <ASelectOption value="FORWARD">远期曲线</ASelectOption>
            </ASelect>
          </ACol>
          <ACol :span="6">
            <AInput v-model:value="searchForm.currency" placeholder="请输入币种" allow-clear />
          </ACol>
          <ACol :span="6">
            <ASpace>
              <AButton type="primary" @click="handleSearch">
                <template #icon>
                  <icon-carbon:search />
                </template>
                查询
              </AButton>
              <AButton @click="handleReset">
                <template #icon>
                  <icon-carbon:reset />
                </template>
                重置
              </AButton>
              <AButton type="primary" @click="handleAdd">
                <template #icon>
                  <icon-carbon:add />
                </template>
                新增
              </AButton>
            </ASpace>
          </ACol>
        </ARow>
      </div>

      <!-- 表格区域 -->
      <ATable
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        size="small"
        :scroll="{ x: 1500 }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <ATag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'action'">
            <ASpace>
              <AButton type="link" size="small" danger @click="handleDelete(record as CurveConfig)">删除</AButton>
            </ASpace>
          </template>
        </template>
      </ATable>
    </ACard>

    <!-- 新增/编辑模态框 -->
    <AModal v-model:open="modalVisible" title="新增曲线映射" :width="800" @ok="handleSubmit" @cancel="handleCancel">
      <AForm ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <AFormItem label="币种" name="currency">
          <AInput v-model:value="formData.currency" placeholder="请输入币种" @change="onCurrencyChange" />
        </AFormItem>
        <AFormItem label="产品类别" name="type">
          <ASelect
            v-model:value="formData.type"
            placeholder="请选择产品类别"
            :options="productTypeOptions"
            allow-clear
          />
        </AFormItem>
        <AFormItem label="FX合约" name="fxContract">
          <AInput v-model:value="formData.fxContract" placeholder="请输入FX合约" />
        </AFormItem>
        <AFormItem label="指标" name="idx">
          <AInput v-model:value="formData.idx" placeholder="请输入指标" />
        </AFormItem>
        <AFormItem label="类型学" name="typology">
          <AInput v-model:value="formData.typology" placeholder="请输入类型学" />
        </AFormItem>
        <AFormItem label="交易台" name="desk">
          <AInput v-model:value="formData.desk" placeholder="请输入交易台" />
        </AFormItem>
        <AFormItem label="生成器" name="generator">
          <AInput v-model:value="formData.generator" placeholder="请输入生成器" />
        </AFormItem>
        <AFormItem label="计算方式" name="curveType">
          <ASelect v-model:value="formData.curveType" placeholder="请选择曲线类型">
            <!-- <ASelectOption value="YIELD">收益率曲线</ASelectOption> -->
            <ASelectOption value="DISCOUNT">贴现曲线</ASelectOption>
            <ASelectOption value="FORWARD">远期曲线</ASelectOption>
          </ASelect>
        </AFormItem>
        <AFormItem label="曲线名称" name="curveName">
          <ASelect v-model:value="formData.curveName" placeholder="请选择曲线名称" show-search>
            <ASelectOption v-for="option in curveDefinitionOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </ASelectOption>
          </ASelect>
        </AFormItem>
        <AFormItem label="描述" name="description">
          <ATextarea v-model:value="formData.description" placeholder="请输入描述" :rows="3" />
        </AFormItem>
        <AFormItem label="配置参数" name="configParams">
          <ATextarea v-model:value="formData.configParams" placeholder="请输入JSON格式的配置参数" :rows="4" />
        </AFormItem>
        <AFormItem label="状态" name="status">
          <ARadioGroup v-model:value="formData.status">
            <ARadio :value="1">启用</ARadio>
            <ARadio :value="0">禁用</ARadio>
          </ARadioGroup>
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}

/* 表格行间距优化 */
:deep(.ant-table-tbody > tr > .ant-table-cell) {
  padding: 8px 16px !important;
}

:deep(.ant-table-thead > tr > th) {
  padding: 16px 16px !important;
}
</style>
